package staff.io;

import static staff.util.XmlUtils.XML_EMPLOYE_TAG;
import static staff.util.XmlUtils.XML_ROOT_EMPLOYE_TAG;
import static staff.util.XmlUtils.saveXmlDocumentToFile;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import staff.logic.Employee;

/** Class for saving employes to XML. Using DOM. */
public class DOMEmployeSaver implements EmployeSaver {
    private Document newDocument;
    private Element rootElement;
    private String fileName;

    public DOMEmployeSaver(String fileName) throws ParserConfigurationException, IOException {
        this.fileName = fileName;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
        newDocument = documentBuilder.newDocument();
        rootElement = newDocument.createElement(XML_ROOT_EMPLOYE_TAG);
    }

    public void saveNext(Employee employe) {
        Element employeElement = newDocument.createElement(XML_EMPLOYE_TAG);
        for (Employee.FieldTag fieldTag : Employee.FieldTag.values()) {
            // save employe's field
            Element field = newDocument.createElement(fieldTag.toString());
            String value = employe.getParamByName(fieldTag.toString());
            field.appendChild(newDocument.createTextNode(value));
            // append field node to employe node
            employeElement.appendChild(field);
        }
        // save employe node to root node
        rootElement.appendChild(employeElement);
    }

    /** Write document */
    public void close() {
        newDocument.appendChild(rootElement);
        try {
            saveXmlDocumentToFile(newDocument, fileName);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        } catch (TransformerException ex) {
            throw new IllegalStateException(ex);
        }
    }

}
